package peer.model.connections;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Scanner;

import model.dto.NetPackage;
import model.xml.XMLCodec;

public class NetPackagesManager {

	/**
	 * @author Silvio Vilerino
	 * @param aliases XML alias Map for example ("request", model.dto.RequestDTO)
	 * @param in Scanner from which response will be readed
	 * @param out OutputStream where the request will be sent through
	 * @param requestPackage NetPackage to be sent
	 * @return NetPackage Response from Server
	 * @return null if no response
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static NetPackage sendPackage(Map<String, Class> aliases, Scanner in, OutputStream out, NetPackage requestPackage) throws IOException{
		XMLCodec.toXML(aliases, requestPackage, out);
		if(in.hasNextLine()){
			try{
				return (NetPackage) XMLCodec.parseXml(aliases, in.nextLine().replaceAll("_barraN_", "\n").replaceAll("_barraR_", "\r"));
			}catch(ClassCastException e){
				e.printStackTrace(System.err);
			}
		}
		return null;
	}


	/**
	 * @author Silvio Vilerino
	 * @param aliases XML alias Map for example ("request", model.dto.RequestDTO)
	 * @param in Scanner from which response will be readed
	 * @param out OutputStream where the request will be sent through
	 * @param Object obj to be sent
	 * @return Object Response from Server
	 * @return null if no response
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static Object sendObject(Map<String, Class> aliases, Scanner in, OutputStream out, Object obj) throws IOException{
		XMLCodec.toXML(aliases, obj, out);
		if(in.hasNextLine()){
			return XMLCodec.parseXml(aliases, in.nextLine().replaceAll("_barraN_", "\n").replaceAll("_barraR_", "\r"));
		}
		return null;
	}

}
